﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EquipSecs300
{
    /// <summary>
    /// 使用例子：
    /// DataSaveInCsv test = new DataSaveInCsv(path,header) //初始化生成csv文件并且再第一行写入标题  中间用间隔隔开
    /// 
    /// 写入数据
    /// test.Write(LogData) 
    /// test.Record() 
    /// 
    /// </summary>
    public class CsvHelper
    {
        object o1 = new object();
        private Queue<string> RecordDataContent = new Queue<string>();
        string FilePath;
        public CsvHelper(string FilePath)
        {
            this.FilePath = FilePath;
        }
        public CsvHelper(string FilePath, string DataHeader)
        {
            if (!FilePath.Contains(".csv"))
            {
                FilePath = FilePath + ".csv";
            }
            this.FilePath = FilePath;

            CreateFile(FilePath, DataHeader);
        }
        private void CreateFile(string FilePath, string DataHeader)
        {
            string[] s = new string[100];
            s = FilePath.Split('\\');
            int index = s.Count() - 2;
            string Path = s[0];
            if (!File.Exists(FilePath))
            {

                for (int i = 1; i <= index; i++)
                {
                    //Path = Path + "\\" + s[i];
                    Path = string.Format("{0}\\{1}", Path, s[i]);
                    if (Directory.Exists(Path) == false)
                    {
                        Directory.CreateDirectory(Path);
                    }
                }
                Write(DataHeader);
            }
        }
        public void Write(string inputs)
        {
            lock (o1)
            {
                RecordDataContent.Enqueue(inputs);
            }
        }
        public void Record()
        {
            try
            {
                if (RecordDataContent.Count == 0)
                {
                    return;
                }

                FileStream fs = new FileStream(FilePath, FileMode.Append);
                StreamWriter sw = new StreamWriter(fs, Encoding.Default);
                string s1;
                while (RecordDataContent.Count > 0)
                {
                    lock (o1)
                    {
                        s1 = RecordDataContent.Dequeue();
                        sw.Write(s1 + "\n");
                    }
                }
                sw.Close();
                fs.Close();
            }
            catch (Exception)
            {

            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Columns">读取长度为Columns的行；不设置全部读取</param>
        /// <returns></returns>
        public DataTable ReadCsvFile(int Columns = -1)
        {
            string filePath = FilePath;
            DataTable dt = new DataTable();
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs, Encoding.UTF8);

            string strLine = null;
            string[] arrayLine = null;
            bool isFirst = true;
            int dtColumns = 0;

            while ((strLine = sr.ReadLine()) != null)
            {
                strLine = strLine.Trim();
                arrayLine = strLine.Split(',');
                if (!(Columns == -1))
                {
                    if (arrayLine.Length != Columns)
                    {
                        continue;
                    }
                }

                if (isFirst)  
                {
                    dtColumns = arrayLine.Length;
                    for (int i = 0; i < dtColumns; i++)
                    {
                        if (dt.Columns.Contains(arrayLine[i]))
                        {
                            dt.Columns.Add(arrayLine[i] + i);
                        }
                        else
                        {
                            dt.Columns.Add(arrayLine[i]);
                        }
                    }
                    isFirst = false;
                }
                else  
                {
                    DataRow dataRow = dt.NewRow();
                    for (int j = 0; j < dtColumns; j++)
                    {
                        if (arrayLine.Length > j)
                        {
                            dataRow[j] = arrayLine[j];
                        }
                    }
                    dt.Rows.Add(dataRow);
                }
            }
            sr.Close();
            fs.Close();

            return dt;
        }
    }

}
